package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.LogToDB
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Encoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @use 获取法大大用户状态
 *
 */

public class apiGetFDDCustomerStatus implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetFDDCustomerStatus.class);
    private static String APPKEY;
    private static String APPID;
    private static String URL;
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JSONObject jsonPara = new JSONObject();
        // 初始化返回参数
        JSONObject result = new JSONObject();
        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {

            APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");
            APPID = KHDBConfig.getParam(eliteBean, "FDDID");
            URL = KHDBConfig.getAPIURL(eliteBean, "fddurl");
            HashMap<String, Object> headMap = new HashMap<>();
            headMap.put("Content-Type", "application/json");
            JSONObject inJson = JSONObject.fromObject(callJson);

            //获取客户编号
            String customerID = inJson.getString("customerID");
            //获取客户类型
                String customertype = inJson.getString("customerType");//个人/公司

            if(customertype == '个人'){
                URL += "/certification/person/get-status";
            }else if(customertype == '公司'){
                URL += "/certification/company/get-status";
            }else{
                result.put("code", 1009);
                result.put("msg", "未知客户类型："+customertype);
            }

            log.info("[customertype]:" + customertype + " [URL]:" + URL);

            jsonPara.put("customerId", customerID);
            String bizContent = getbizContent(jsonPara.toString());
            bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
            JSONObject jsons = new JSONObject();
            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsons.put("timestamp", datetime);
            jsons.put("bizContent", bizContent);
            jsons.put("signType", "SHA256");
            jsons.put("appId", APPID);
            String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
            signString = signString.replace("\\n", "");

            String signstr1 = Util.getSHA256Str(signString).toUpperCase();
            String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
            String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
            jsons.put("sign", sign);
            log.debug("客户认证状态查下参数:" + jsons.toString().replace("\\n", ""));
            String Assemblys = Util.doHttpPostUseHead(URL, jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
            result = JSONObject.fromObject(Assemblys);
        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部认证转发", "apiCustomerRegist", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        return result.toString();
    }

    //获取bizContent
    public String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }
}
